import java.sql.*;

public class DBConnection {
    private static final String URL = "jdbc:mysql://127.0.0.1:3306/chat_system";
    private static final String USER = "root"; // 替换为你的数据库用户名
    private static final String PASSWORD = "ludan"; // 替换为你的数据库密码

    // 获取数据库连接
    public static Connection getConnection() throws SQLException {
        return DriverManager.getConnection(URL, USER, PASSWORD);
    }

    // 验证用户登录
    public static boolean validateUser(String username, String password) {
        String query = "SELECT * FROM users WHERE username = ? AND password = ?";

        try (Connection conn = getConnection();
             PreparedStatement pstmt = conn.prepareStatement(query)) {

            pstmt.setString(1, username);
            pstmt.setString(2, password);

            try (ResultSet rs = pstmt.executeQuery()) {
                return rs.next(); // 如果有结果，返回true
            }
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        }
    }

    // 更新用户在线状态
    public static void updateOnlineStatus(String username, boolean isOnline) {
        String query = "UPDATE users SET online_status = ?, last_login = ? WHERE username = ?";

        try (Connection conn = getConnection();
             PreparedStatement pstmt = conn.prepareStatement(query)) {

            pstmt.setBoolean(1, isOnline);
            pstmt.setTimestamp(2, new Timestamp(System.currentTimeMillis()));
            pstmt.setString(3, username);

            pstmt.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    // 获取在线用户列表
    public static String getOnlineUsers() {
        String query = "SELECT username FROM users WHERE online_status = true";
        StringBuilder onlineUsers = new StringBuilder();

        try (Connection conn = getConnection();
             PreparedStatement pstmt = conn.prepareStatement(query);
             ResultSet rs = pstmt.executeQuery()) {

            while (rs.next()) {
                if (onlineUsers.length() > 0) {
                    onlineUsers.append(",");
                }
                onlineUsers.append(rs.getString("username"));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return onlineUsers.toString();
    }
}
